import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleServer {
    public static void main(String[] args) {
        int port = 12345; // 服务器监听的端口号
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器正在监听端口 " + port);
            while (true) {
                // 等待客户端连接
                try (Socket clientSocket = serverSocket.accept();
                     BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                     PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
                    System.out.println("客户端已连接: " + clientSocket.getInetAddress());
                    String inputLine;
                    while ((inputLine = in.readLine())!= null) {
                        System.out.println("收到客户端消息: " + inputLine);
                        // 回复客户端
                        String outputLine = "服务器回复: " + inputLine;
                        out.println(outputLine);
                        if (inputLine.equalsIgnoreCase("exit")) {
                            break;
                        }
                    }
                } catch (IOException e) {
                    System.out.println("客户端连接出现问题: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.out.println("服务器启动失败: " + e.getMessage());
        }
    }
}